package com.xueyi.aixihu.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSON;
import com.xueyi.aixihu.entity.generatedMapper.AxhFinanceMapper;
import com.xueyi.aixihu.entity.generatedMapper.AxhFinanceReportCommunityMapper;
import com.xueyi.aixihu.entity.generatedMapper.AxhFinanceReportVillageMapper;
import com.xueyi.aixihu.entity.po.AxhFinance;
import com.xueyi.aixihu.entity.po.AxhFinanceReportCommunity;
import com.xueyi.aixihu.entity.po.AxhFinanceReportVillage;
import com.xueyi.aixihu.entity.po.DtNewsSort;
import com.xueyi.aixihu.entity.vo.*;
import com.xueyi.aixihu.exception.SzException;
import com.xueyi.aixihu.mapper.FinanceMapper;
import com.xueyi.aixihu.reqeust.FinancePublicListReq;
import com.xueyi.aixihu.reqeust.FinanceReportReq;
import com.xueyi.aixihu.reqeust.FinanceReq;
import com.xueyi.aixihu.reqeust.base.PageLimitReq;
import com.xueyi.aixihu.response.DtOneFinanceLogRes;
import com.xueyi.aixihu.service.IFinanceReportService;
import com.xueyi.aixihu.status.FinanceStatus;
import com.xueyi.aixihu.status.IsStatus;
import com.xueyi.aixihu.status.SystemCode;
import com.xueyi.aixihu.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 描述 财务报表实现类
 *
 * @auther 俞烨
 * @date 2022-08-16 13
 */
@Service
@Slf4j
public class FinanceReportServiceImpl implements IFinanceReportService {

    @Autowired
    AxhFinanceReportCommunityMapper axhFinanceReportCommunityMapper;
    @Autowired
    AxhFinanceReportVillageMapper axhFinanceReportVillageMapper;
    @Autowired
    FinanceMapper financeMapper;
    @Autowired
    AxhFinanceMapper axhFinanceMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importDataByExcel(MultipartFile file, Integer financeType) throws IOException, SzException {
        try {
            parseCommunityExcel(file, financeType);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SzException(SystemCode.QUERY_CHECK_ERROR, "报表错误，请重新上传");
        }
    }

    @Override
    public FinanceAuditSizeVo findFinanceAuditSize(FinanceReq financeReq) {

        // 根据用户的自身角色查看该用户对于代办应该能查到什么状态的数据
        DtUsersVo currentUser = DtUsersVo.findCurrentUser();

        financeReq.format();

        // 查询代办和驳回的数据信息
        return financeMapper.findFinanceAuditSize(financeReq, currentUser.findUserManageAreaId(), currentUser.findUserFinanceLookCurrentStatus(1), currentUser.findUserFinanceLookCurrentStatus(2), currentUser.findUserFinanceLookCurrentStatus(3));
    }

    @Override
    public List<FinanceAuditVo> findFinanceAuditList(FinanceReq financeReq) throws SzException {

        financeReq.formatNew();
        // 根据用户的自身角色查看该用户对于代办应该能查到什么状态的数据
        DtUsersVo currentUser = DtUsersVo.findCurrentUser();
        String userFinanceLookCurrentStatus = null;
        if (financeReq.getFinanceType() != null) {
            userFinanceLookCurrentStatus = currentUser.findUserFinanceLookCurrentStatus(financeReq.getFinanceType());
        } else {
            userFinanceLookCurrentStatus = currentUser.findUserFinanceLookCurrentStatus(1);
            userFinanceLookCurrentStatus = StringUtils.hasLength(userFinanceLookCurrentStatus) ? userFinanceLookCurrentStatus + "," + currentUser.findUserFinanceLookCurrentStatus(2) : currentUser.findUserFinanceLookCurrentStatus(2);
            userFinanceLookCurrentStatus = StringUtils.hasLength(userFinanceLookCurrentStatus) ? userFinanceLookCurrentStatus + "," + currentUser.findUserFinanceLookCurrentStatus(3) : currentUser.findUserFinanceLookCurrentStatus(3);
        }

        List<FinanceAuditVo> financeAuditList = financeMapper.findFinanceAuditList(financeReq, currentUser.findUserManageAreaId(), financeReq.getFb() != null ? null : userFinanceLookCurrentStatus);
        if (!CollectionUtils.isEmpty(financeAuditList)) {
            for (FinanceAuditVo financeAuditVo : financeAuditList) {
                financeAuditVo.setCurrentStatusStr(FinanceStatus.getAuditMsg(financeAuditVo.getCurrentStatus(), financeAuditVo.getAreaType()));
            }
        }
        return financeAuditList;
    }

    @Override
    public Integer findFinanceSizeByStatus(FinanceReq financeReq) throws SzException {

        financeReq.formatNew();
        DtUsersVo currentUser = DtUsersVo.findCurrentUser();
        return financeMapper.findFinanceAuditSizeByStatus(financeReq, currentUser.findUserManageAreaId(), currentUser.findUserFinanceLookCurrentStatus(financeReq.getFinanceType()));
    }

    @Override
    public FinanceExpenseSizeVo findFinanceExpenseSizeVo(FinanceExpenseReq financeExpenseReq) {

        financeExpenseReq.format();
        FinanceExpenseSizeVo financeExpenseSizeVo = financeMapper.findFinanceExpenseSizeVo(financeExpenseReq, DtUsersVo.findCurrentUser().findUserManageAreaId());

        // 判断当前登陆的用户的角色列表是否有村和社区
        financeExpenseSizeVo.setCunFlag(DtUsersVo.findCurrentUser().getRoleList().contains(DtUsersVo.roleIdList.get(0) + "") ? 1 : 0);
        financeExpenseSizeVo.setSqFlag(DtUsersVo.findCurrentUser().getRoleList().contains(DtUsersVo.roleIdList.get(1) + "") ? 1 : 0);

        return financeExpenseSizeVo;
    }


    @Override
    public List<FinanceAuditVo> findFinanceExpenseList(FinanceReq financeReq) {

        financeReq.format();
        // 根据用户的自身角色查看该用户对于代办应该能查到什么状态的数据
        DtUsersVo currentUser = DtUsersVo.findCurrentUser();
        String currentStatus = financeReq.getFinanceType() == null ? null : financeReq.getFinanceType() == -1 ? null : financeReq.getFinanceType() == 1 ? "4" : financeReq.getFinanceType() == 2 ? "1,2,3" : financeReq.getFinanceType() == 3 ? "-1,-2,-3" : "0";
        List<FinanceAuditVo> financeAuditList = financeMapper.findFinanceAuditList(financeReq, currentUser.findUserManageAreaId(), currentStatus);
        if (!CollectionUtils.isEmpty(financeAuditList)) {
            for (FinanceAuditVo financeAuditVo : financeAuditList) {
                financeAuditVo.setFinanceStatus(FinanceAuditVo.getFinalStatus(financeAuditVo.getCurrentStatus()));
                financeAuditVo.setFinanceStatusStr(FinanceAuditVo.financeStatusStr(financeAuditVo.getFinanceStatus()));
                financeAuditVo.setCurrentStatusStr(FinanceStatus.getAuditMsg(financeAuditVo.getCurrentStatus(), financeAuditVo.getAreaType()));
            }
        }

        return financeAuditList;
    }

    @Override
    public Integer findFinanceExpenseSizeByStatus(FinanceReq financeReq) throws SzException {

        financeReq.format();
        // 根据用户的自身角色查看该用户对于代办应该能查到什么状态的数据
        DtUsersVo currentUser = DtUsersVo.findCurrentUser();
        String currentStatus = financeReq.getFinanceType() == null ? null : financeReq.getFinanceType() == -1 ? null : financeReq.getFinanceType() == 1 ? "4" : financeReq.getFinanceType() == 2 ? "1,2,3" : financeReq.getFinanceType() == 3 ? "-1,-2,-3" : "0";
        return financeMapper.findFinanceAuditSizeByStatus(financeReq, currentUser.findUserManageAreaId(), currentStatus);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateFinancePublicStatus(Integer id, Integer publicStatus) throws SzException {


        AxhFinance axhFinance = axhFinanceMapper.selectByPrimaryKey(id);

        if (publicStatus == 1 && !axhFinance.getCurrentStatus().equals(FinanceStatus.PASS_AUDIT.type)) {

            throw new SzException(SystemCode.QUERY_CHECK_ERROR, "未通过审核的报表暂时不能公开");
        }

        // 修改财务报表
        financeMapper.updateFinancePublicStatus(id, publicStatus, DtUsersVo.findCurrentUser().findUserManageAreaId());

        LogUtil.buildFinanceLog(id, "【财务报销】用户" + DtUsersVo.findCurrentUser().getUsername() + "修改了报表的公开状态（修改成" + (publicStatus == 1 ? "公开" : "隐藏") + "）", DtUsersVo.findCurrentUser(), axhFinance.getFromToAreaId(), FinanceStatus.COMMAND_UPDATE.type);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitFinance(Integer id) throws SzException {

        String userManageAreaId = DtUsersVo.findCurrentUser().findUserManageAreaId();
        // 查询报表的信息
        AxhFinance finance = findFinance(id, userManageAreaId, true);

        // 修改报表的状态
        financeMapper.updateFinanceStatus(id, userManageAreaId, FinanceStatus.ONE_AUDIT.type);

        // 添加日志
        LogUtil.buildFinanceLog(id, "【财务报销】用户" + DtUsersVo.findCurrentUser().getUsername() + "提交了报表审核.", DtUsersVo.findCurrentUser(), finance.getFromToAreaId(), FinanceStatus.ONE_AUDIT.type);

        // 发送模版消息
        sendWeChatWarnMsg(finance, FinanceStatus.ONE_AUDIT, null, 0, "您有一条财务审核通知");
    }

    @Autowired
    HttpServletRequest request;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditFinance(Integer id, String remark, Integer auditType) throws SzException {

        String userManageAreaId = DtUsersVo.findCurrentUser().findUserManageAreaId();
        AxhFinance finance = findFinance(id, userManageAreaId, false);


        // 判断是否是副本的审核
        if ("1".equals(request.getParameter("fb"))) {
            String tableName = finance.getAreaType() == 1 ? "axh_finance_report_community" : "axh_finance_report_village";
            // 说明是副本的审核
            if (auditType.equals(IsStatus.YES)) {
                // 审核通过
                // 需要将副本信息替换成真的数据
                financeMapper.updateFinanceAndRejectMsgFb(finance.getId(), 0);
                financeMapper.findOldId(finance.getId(), tableName);
                /*if (!CollectionUtils.isEmpty(oldId)) {
                    for (Integer oId : oldId) {
                        // 查询这个oId的副本Id为多少
                        Integer beLongFbId = financeMapper.findBeLongIdByOldId(oId, tableName);
                        // 修改对应的数据信息
                        financeMapper.updateParentId(oId, tableName , Math.negateExact(beLongFbId));

                    }
                }*/
                financeMapper.useFb(finance.getId(), tableName);
                financeMapper.clearFbStatus(finance.getId(), tableName);
            }
            // 审核通过发送短信通知
            List<DtUsersVo> dtUserByRoles = financeMapper.findDtUserByRoles(finance.getAreaType().equals(2) ? DtUsersVo.roleIdList.get(0) + "" : DtUsersVo.roleIdList.get(1) + "", finance.getFromToAreaId());
            sendWeChatWarnMsg(finance, null, dtUserByRoles, 1, auditType == 0 ? "二次修改被驳回，原因为: " + remark : "二次修改的报表数据通过");
            financeMapper.rejectFbFinance(id, auditType == 1 ? null : remark, 0);

            // 添加日志
            LogUtil.buildFinanceLog(id, "【财务报销】用户" + DtUsersVo.findCurrentUser().getUsername() + "审核了二次修改报表，结果为:  " + (auditType.equals(IsStatus.YES) ? "通过" : "拒绝"), DtUsersVo.findCurrentUser(), finance.getFromToAreaId(), FinanceStatus.COMMAND_UPDATE.type, remark);
            return;
        }

        // 当前用户最大的角色权限
        Integer userMaxRole = DtUsersVo.findCurrentUser().findUserMaxRole();
        FinanceStatus finalStatus = FinanceStatus.CAO_GAO;
        if (userMaxRole.equals(DtUsersVo.roleIdList.get(2)) || userMaxRole.equals(DtUsersVo.roleIdList.get(3))) {
            // 代理会计进行审核
            finalStatus = auditType.equals(IsStatus.YES) ? FinanceStatus.TWO_AUDIT : FinanceStatus.TURN_ZERO;
            financeMapper.updateFinanceStatus(id, userManageAreaId, finalStatus.type);
        } else if (userMaxRole.equals(DtUsersVo.roleIdList.get(4)) || userMaxRole.equals(DtUsersVo.roleIdList.get(5))) {
            // 主任进行审核
            finalStatus = auditType.equals(IsStatus.YES) ? FinanceStatus.THREE_AUDIT : FinanceStatus.TURN_ONE;
            financeMapper.updateFinanceStatus(id, userManageAreaId, finalStatus.type);
        } else if (userMaxRole.equals(DtUsersVo.roleIdList.get(6))) {
            // 领导进行审核
            finalStatus = auditType.equals(IsStatus.YES) ? FinanceStatus.PASS_AUDIT : FinanceStatus.TURN_TWO;
            financeMapper.updateFinanceStatus(id, userManageAreaId, finalStatus.type);
        } else if (userMaxRole.equals(DtUsersVo.roleIdList.get(1)) || userMaxRole.equals(DtUsersVo.roleIdList.get(0))) {
            // 村社区重新审核
            finalStatus = FinanceStatus.ONE_AUDIT;
            financeMapper.updateFinanceStatus(id, userManageAreaId, finalStatus.type);
        } else {
            throw new SzException(SystemCode.QUERY_CHECK_ERROR, "当前报表还在草稿状态");
        }

        // 添加日志
        LogUtil.buildFinanceLog(id, "【财务报销】用户" + DtUsersVo.findCurrentUser().getUsername() + "审核了报表，状态为: " + finalStatus.msg, DtUsersVo.findCurrentUser(), finance.getFromToAreaId(), finalStatus.type, remark);

        // 发送模版消息
        sendWeChatWarnMsg(finance, finalStatus, null, 0, "您有一条财务审核通知");
    }

    @Override
    public void updateFinance(Integer id, String financeTitle, String month) throws SzException {

        DtUsersVo currentUser = DtUsersVo.findCurrentUser();

        // 查询报表
        AxhFinance finance = findFinance(id, currentUser.findUserManageAreaId(), false);


        AxhFinance axhFinance = new AxhFinance();
        axhFinance.setFinanceTitle(financeTitle);
        axhFinance.setCreateTime(DateUtil.parse(month, "yyyy-MM"));
        axhFinance.setLastUpdateTime(new Date());
        axhFinance.setId(id);
        axhFinanceMapper.updateByPrimaryKeySelective(axhFinance);

        LogUtil.buildFinanceLog(id, "【财务报销】用户" + currentUser.getUsername() + "修改了财务报表的基本信息（名称、日期）等。", currentUser, finance.getFromToAreaId(), FinanceStatus.COMMAND_UPDATE.type);
    }

    @Override
    public void delOrRecoverReport(Integer id, Integer status) throws SzException {

        DtUsersVo currentUser = DtUsersVo.findCurrentUser();
        AxhFinance finance = findFinance(id, currentUser.findUserManageAreaId(), false);
        financeMapper.delOrRecoverReport(id, status);

        LogUtil.buildFinanceLog(id, "【财务报销】用户" + currentUser.getUsername() + (status == 0 ? "删除" : "恢复") + "了财务报表.", currentUser, finance.getFromToAreaId(), FinanceStatus.COMMAND_UPDATE.type);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void uploadFinanceAccessory(Integer id, Integer lineId, String accessory) throws SzException {

        DtUsersVo currentUser = DtUsersVo.findCurrentUser();
        AxhFinance finance = findFinance(id, currentUser.findUserManageAreaId(), false);
        String tableName = finance.getAreaType() == 1 ? "axh_finance_report_community" : "axh_finance_report_village";
        if ("1".equals(request.getParameter("fb"))) {
            FinanceReportBase financeReportBase = null;
            // 查询这一列的基本信息
            if (finance.getAreaType() == 1) {
                financeReportBase = financeMapper.findLine(lineId, tableName);
            } else {
                financeReportBase = financeMapper.findLine2(lineId, tableName);
            }

            if (financeReportBase != null) {
                // 判断当前的凭证是否有副本的信息，如果当前的凭证没有副本的信息则需要创建副本信息，然后再去添加凭证信息
                financeReportBase.setAccessory(accessory);
                if (financeReportBase.getFbStatus() == null || financeReportBase.getFbStatus() == 0) {
                    // 说明不是副本的信息
                    financeReportBase.setFb(1);
                    if (finance.getAreaType() == 1) {
                        updateOrSaveFinanceLineCommunity((AxhFinanceReportCommunity) financeReportBase);
                    } else {
                        updateOrSaveFinanceLineVillage((AxhFinanceReportVillage) financeReportBase);
                    }
                } else {
                    // 判断有没有属于这行的belongId的信息
                    Integer lineBeLongId = financeMapper.findBeLongIdByOldId(financeReportBase.getId(), tableName);
                    // 判断是通过beLongId修改还是直接通过id修改
                    if (lineBeLongId != null) {
                        financeMapper.uploadFinanceAccessory2(lineBeLongId, accessory, tableName);
                    } else {
                        financeMapper.uploadFinanceAccessory(lineId, accessory, tableName);
                    }
                }
            }
        } else {
            financeMapper.uploadFinanceAccessory(lineId, accessory, tableName);
        }
        LogUtil.buildFinanceLog(id, "【财务报销】用户" + currentUser.getUsername() + "上传了财务报表的附件信息.", currentUser, finance.getFromToAreaId(), FinanceStatus.COMMAND_UPDATE.type);
    }

    @Override
    public void updateOrSaveFinanceLineCommunity(AxhFinanceReportCommunity axhFinanceReportCommunity) throws SzException {

        if (axhFinanceReportCommunity.getId() == null && axhFinanceReportCommunity.getPid() == null) {
            throw new SzException(SystemCode.QUERY_CHECK_ERROR, "父ID不能为空");
        }

        DtUsersVo currentUser = DtUsersVo.findCurrentUser();

        AxhFinance finance = findFinance(axhFinanceReportCommunity.getFinanceId(), currentUser.findUserManageAreaId(), false);

        String msg = "新增";
        if (axhFinanceReportCommunity.getId() == null || "1".equals(axhFinanceReportCommunity.getFb() + "")) {
            // 说明是增加一列
            // 判断是FB还是什么
            if ("1".equals(axhFinanceReportCommunity.getFb() + "")) {
                // 需要指定FB的BelongId为之前的id
                // 查询出凭证的内容。
                // 修改本行的状态，标记有副本的状态
                axhFinanceReportCommunity.setFbStatus(3);
                if (axhFinanceReportCommunity.getId() != null) {
                    AxhFinanceReportCommunity axhFinanceReportCommunity1 = axhFinanceReportCommunityMapper.selectByPrimaryKey(axhFinanceReportCommunity.getId());
                    axhFinanceReportCommunity.setBeLongId(axhFinanceReportCommunity.getId());
                    axhFinanceReportCommunity.setAccessory(StringUtils.hasLength(axhFinanceReportCommunity.getAccessory()) ? axhFinanceReportCommunity.getAccessory() : axhFinanceReportCommunity1.getAccessory());
                    financeMapper.updateFbStatus(axhFinanceReportCommunity.getId(), "axh_finance_report_community", 2);
                    // 删除之前所有的其他副本
                    financeMapper.deleteFb(axhFinanceReportCommunity.getId(), "axh_finance_report_community");
                }
                financeMapper.updateFinanceFb(axhFinanceReportCommunity.getFinanceId(), 1);
                axhFinanceReportCommunity.setId(null);
            }
            axhFinanceReportCommunityMapper.insertSelective(axhFinanceReportCommunity);
        } else {
            msg = "修改";
            axhFinanceReportCommunity.setLastUpdateTime(new Date());
            axhFinanceReportCommunity.setFinanceId(null);
            axhFinanceReportCommunityMapper.updateByPrimaryKeySelective(axhFinanceReportCommunity);
        }

        if ("资产总计".equals(axhFinanceReportCommunity.getLineName())) {
            finance.setBorrowTotalMoney(axhFinanceReportCommunity.getEndMoney());
        }
        if ("负债和净资产总计".equals(axhFinanceReportCommunity.getLineName())) {
            finance.setLoanTotalMoney(axhFinanceReportCommunity.getEndMoney());
        }

        axhFinanceMapper.updateByPrimaryKeySelective(finance);

        LogUtil.buildFinanceLog(axhFinanceReportCommunity.getId(), "【财务报销】用户" + currentUser.getUsername() + msg + "财务报表的详细信息.", currentUser, finance.getFromToAreaId(), FinanceStatus.COMMAND_UPDATE.type);
    }

    @Override
    public void updateOrSaveFinanceLineVillage(AxhFinanceReportVillage axhFinanceReportVillage) throws SzException {
        DtUsersVo currentUser = DtUsersVo.findCurrentUser();

        AxhFinance finance = findFinance(axhFinanceReportVillage.getFinanceId(), currentUser.findUserManageAreaId(), false);
        String msg = "新增";
        if (axhFinanceReportVillage.getId() == null || "1".equals(axhFinanceReportVillage.getFb() + "")) {

            // 判断是FB还是什么
            if ("1".equals(axhFinanceReportVillage.getFb() + "")) {
                axhFinanceReportVillage.setFbStatus(3);
                if (axhFinanceReportVillage.getId() != null) {
                    // 需要指定FB的BelongId为之前的id
                    AxhFinanceReportVillage axhFinanceReportVillage1 = axhFinanceReportVillageMapper.selectByPrimaryKey(axhFinanceReportVillage.getId());
                    axhFinanceReportVillage.setAccessory(StringUtils.hasLength(axhFinanceReportVillage.getAccessory()) ? axhFinanceReportVillage.getAccessory() : axhFinanceReportVillage1.getAccessory());
                    axhFinanceReportVillage.setBeLongId(axhFinanceReportVillage.getId());
                    // 修改本行的状态，标记有副本的状态
                    financeMapper.updateFbStatus(axhFinanceReportVillage.getId(), "axh_finance_report_village", 2);
                    financeMapper.deleteFb(axhFinanceReportVillage.getId(), "axh_finance_report_village");
                }
                financeMapper.updateFinanceFb(axhFinanceReportVillage.getFinanceId(), 1);
                axhFinanceReportVillage.setId(null);
            }
            // 说明是增加一列
            axhFinanceReportVillageMapper.insertSelective(axhFinanceReportVillage);
        } else {
            msg = "修改";
            axhFinanceReportVillage.setLastUpdateTime(new Date());
            axhFinanceReportVillage.setFinanceId(null);
            axhFinanceReportVillageMapper.updateByPrimaryKeySelective(axhFinanceReportVillage);
        }

        // 判断是否是合计的信息
        if ("合计".equals(axhFinanceReportVillage.getLineName())) {
            finance.setBorrowTotalMoney(axhFinanceReportVillage.getCurrentBorrow());
            finance.setLoanTotalMoney(axhFinanceReportVillage.getCurrentLoan());
            axhFinanceMapper.updateByPrimaryKeySelective(finance);
        }

        LogUtil.buildFinanceLog(axhFinanceReportVillage.getId(), "【财务报销】用户" + currentUser.getUsername() + msg + "财务报表的详细信息.", currentUser, finance.getFromToAreaId(), FinanceStatus.COMMAND_UPDATE.type);
    }

    @Override
    public void deleteFinanceLine(Integer financeId, Integer lineId) throws SzException {

        DtUsersVo currentUser = DtUsersVo.findCurrentUser();

        AxhFinance finance = findFinance(financeId, currentUser.findUserManageAreaId(), false);
        String tableName = finance.getAreaType() == 1 ? "axh_finance_report_community" : "axh_finance_report_village";

        // 删除数据
        // 判断是否是副本的删除
        if ("1".equals(request.getParameter("fb"))) {
            financeMapper.deleteFbFinanceLine(lineId, tableName);
        } else {
            financeMapper.deleteFinanceLine(lineId, tableName);
            LogUtil.buildFinanceLog(lineId, "【财务报销】用户" + currentUser.getUsername() + "删除了财务报表的一列数据.", currentUser, finance.getFromToAreaId(), FinanceStatus.COMMAND_UPDATE.type);
        }
    }

    @Override
    public FinanceReportSizeVo findFinanceReportSizeVo(FinanceReportReq req) {

        req.format();
        String userFinanceLookCurrentStatus = DtUsersVo.findCurrentUser().findUserFinanceLookCurrentStatus(1);
        String userFinanceLookCurrentStatus2 = DtUsersVo.findCurrentUser().findUserFinanceLookCurrentStatus(2);
        String userFinanceLookCurrentStatus3 = DtUsersVo.findCurrentUser().findUserFinanceLookCurrentStatus(3);

        String tempStr = "";
        if (StringUtils.hasLength(userFinanceLookCurrentStatus)) {
            if (StringUtils.hasLength(tempStr)) {
                tempStr += ",";
            }
            tempStr += userFinanceLookCurrentStatus;
        }

        if (StringUtils.hasLength(userFinanceLookCurrentStatus2)) {
            if (StringUtils.hasLength(tempStr)) {
                tempStr += ",";
            }
            tempStr += userFinanceLookCurrentStatus2;
        }

        if (StringUtils.hasLength(userFinanceLookCurrentStatus3)) {
            if (StringUtils.hasLength(tempStr)) {
                tempStr += ",";
            }
            tempStr += userFinanceLookCurrentStatus3;
        }

        return financeMapper.findFinanceReportSizeVo(req, DtUsersVo.findCurrentUser().findUserManageAreaId(), tempStr);
    }

    @Override
    public DataBlackListVo findDataBlackList(FinanceReportReq req) {

        req.format();
        List<DataBlackListVo.BlackList> blackLists = financeMapper.findFinanceDataBlackList(req, DtUsersVo.findCurrentUser().findUserManageAreaId(),
                StringUtils.hasLength(req.getMonthData()) ? MD5Utils.monthLastDayTime(DateUtil.parse(req.getMonthData(), "yyyy-MM")) : null);

        DataBlackListVo dataBlackListVo = new DataBlackListVo();
        if (!CollectionUtils.isEmpty(blackLists)) {
            dataBlackListVo.setBlackLists(blackLists);
            for (DataBlackListVo.BlackList blackList : blackLists) {
                blackList.setCurrentStatus(blackList.getCurrentStatus() == null ? 0 : blackList.getCurrentStatus());
                if (blackList.getCurrentStatus() == 0) {
                    dataBlackListVo.setNoSize(dataBlackListVo.getNoSize() + 1);
                } else if (blackList.getIsPublic() != null && blackList.getIsPublic() == 1) {
                    blackList.setCurrentStatus(1);
                    dataBlackListVo.setIsPublic(dataBlackListVo.getIsPublic() + 1);
                } else if (blackList.getCurrentStatus() == 4) {
                    blackList.setCurrentStatus(2);
                    dataBlackListVo.setSuccessSize(dataBlackListVo.getSuccessSize() + 1);
                } else {
                    blackList.setCurrentStatus(3);
                    dataBlackListVo.setWaitSize(dataBlackListVo.getWaitSize() + 1);
                }
            }
        }
        return dataBlackListVo;
    }

    @Override
    public List<AxhAuditFinanceLogVo> findFinanceLogList(FinanceReportReq req) {

        req.format();

        return financeMapper.findFinanceLogList(req, DtUsersVo.findCurrentUser().findUserManageAreaId());
    }

    public DtOneFinanceLogRes findOneFinanceLogList(PageLimitReq pageLimitReq) throws SzException {
        pageLimitReq.countStartIndex();
        DtOneFinanceLogRes dtOneFinanceLogRes = new DtOneFinanceLogRes();
        Integer total = financeMapper.findOneFinanceLogListCount(pageLimitReq, DtUsersVo.findCurrentUser().getId());
        List<AxhAuditFinanceLogVo> list = financeMapper.findOneFinanceLogList(pageLimitReq, DtUsersVo.findCurrentUser().getId());
        dtOneFinanceLogRes.setTotal(total);
        dtOneFinanceLogRes.setList(list);
        return dtOneFinanceLogRes;
    }


    @Override
    public List<FinanceFxEchartsVo> financeFxEchartsVo(FinanceReportReq req) {

        req.format();
        List<FinanceFxEchartsVo> financeFxEchartsVos = new ArrayList<>();
        String userManageAreaId = DtUsersVo.findCurrentUser().findUserManageAreaId();
        for (int i = 1; i <= 12; i++) {
            req.setMonthData(i < 10 ? "0" + i : i + "");
            FinanceFxEchartsVo financeFxEchartsVo = financeMapper.financeFxEchartsVo(req, userManageAreaId);
            financeFxEchartsVo = financeFxEchartsVo == null ? new FinanceFxEchartsVo() : financeFxEchartsVo;
            financeFxEchartsVo.setMonth(i + "月");

            financeFxEchartsVos.add(financeFxEchartsVo);
        }
        return financeFxEchartsVos;
    }

    @Override
    public IndexAccountDetail indexAccountDetail() throws SzException {


        DtUsersVo currentUser = DtUsersVo.findCurrentUser();

        IndexAccountDetail indexAccountDetail = new IndexAccountDetail();
        indexAccountDetail.setUName(currentUser.getUsername());
        indexAccountDetail.setUPhoto(currentUser.getAvatar());
        List<DtNewsSort> userManageArea = currentUser.findUserManageArea();
        List<String> areaName = new ArrayList<>();
        if (!CollectionUtils.isEmpty(userManageArea)) {
            for (DtNewsSort dtNewsSort : userManageArea) {
                areaName.add(dtNewsSort.getName());
            }
        }
        indexAccountDetail.setManageAreaList(areaName);
        indexAccountDetail.setLastLoginTime(currentUser.getLastLoginTimeNew());


        // 查询待审批
        FinanceReq financeReq = new FinanceReq();
//        financeReq.setMonth(DateUtil.format(new Date(), "yyyy-MM"));
        financeReq.setFinanceType(1);
        indexAccountDetail.setWaitSize(findFinanceSizeByStatus(financeReq));
        financeReq.setFinanceType(2);
        indexAccountDetail.setWaitSize((indexAccountDetail.getWaitSize() == null ? 0 : indexAccountDetail.getWaitSize()) + findFinanceSizeByStatus(financeReq));
        // 查询村与社区的总数
        String userManageAreaId = DtUsersVo.findCurrentUser().findUserManageAreaId();
        Integer villageAndComSize = financeMapper.findVillageAndComSize(3, userManageAreaId);
        indexAccountDetail.setVillageSize(villageAndComSize == null ? 0 : villageAndComSize);
        Integer communitySize = financeMapper.findVillageAndComSize(16, userManageAreaId);
        indexAccountDetail.setCommunitySize(communitySize == null ? 0 : communitySize);


        IndexAccountDetail.FinanceSize financeSize = financeMapper.findTotalAndPublicSize(3, userManageAreaId);
        indexAccountDetail.setVillageUploadSize(financeSize.getTotalSize() == null ? 0 : financeSize.getTotalSize());
        indexAccountDetail.setVillagePublicSize(financeSize.getPublicSize() == null ? 0 : financeSize.getPublicSize());

        IndexAccountDetail.FinanceSize comSize = financeMapper.findTotalAndPublicSize(16, userManageAreaId);
        indexAccountDetail.setCommunityUploadSize(comSize.getTotalSize() == null ? 0 : comSize.getTotalSize());
        indexAccountDetail.setCommunityPublicSize(comSize.getPublicSize() == null ? 0 : comSize.getPublicSize());
        return indexAccountDetail;
    }

    @Override
    public List<LineReportVo> findReqSizeLineReport(Integer type, String month) {

        // 查询本月所有的数据
        month = StringUtils.isEmpty(month) ? DateUtil.format(new Date(), "yyyy-MM") : month;
        String[] monthSplit = month.split("-");
        int monthInt = Integer.parseInt(monthSplit[1]);
        int year = Integer.parseInt(monthSplit[0]);
        List<LineReportVo> lineReportVos = financeMapper.findReqSizeLineReport(month);
        if (CollectionUtils.isEmpty(lineReportVos)) {
            lineReportVos = new ArrayList<>();
        }
        String currentMonth = DateUtil.format(new Date(), "yyyy-MM");

        Jedis jedis = JedisUtil.getJedis();
        try {
            if (month.equals(currentMonth)) {
                String todayReqSize = jedis.get("TODAY_REQ_SIZE:" + DateUtil.format(new Date(), "yyyy-MM-dd"));
                lineReportVos.add(new LineReportVo(StringUtils.isEmpty(todayReqSize) ? 1 : Integer.parseInt(todayReqSize), DateUtil.format(new Date(), "dd")));
            }
        } finally {
            FinalUtil.unLockAndCloseRedis(jedis);
        }

        // 判断是否是查全部的
        if (type == 1) {
            // 查询七天的
            List<LineReportVo> tempVo = new ArrayList<>();
            for (int i = lineReportVos.size() <= 7 ? 0 : lineReportVos.size() - 7; i < lineReportVos.size() && tempVo.size() < 7; i++) {
                tempVo.add(lineReportVos.get(i));
            }
            if (tempVo.size() < 7) {
                int i = 7 - tempVo.size();
                LineReportVo lineReportVo = lineReportVos.get(0);
                for (int i1 = 0; i1 < i; i1++) {
                    int labelValue = Integer.parseInt(lineReportVo.getLabel()) - (i1 + 1);
                    if (labelValue <= 0) {
                        break;
                    }
                    tempVo.add(0, new LineReportVo(0, labelValue + ""));
                }
            }
            lineReportVos = tempVo;
        } else {
            List<LineReportVo> tempVo = new ArrayList<>();
            int maxDayByYearMonth = getMaxDayByYearMonth(year, monthInt);
            Integer currentDay = 1;
            // 计算maxDayByYearMonth
            if (month.equals(currentMonth)) {
                currentDay = Integer.parseInt(DateUtil.format(new Date(), "dd"));
            }
            if (maxDayByYearMonth != lineReportVos.size()) {

                for (int i = currentDay; i <= maxDayByYearMonth; i++) {
                    lineReportVos.add(new LineReportVo(0, (i <= 9 ? "0" + i : i + "")));
                }

            }
        }
        return lineReportVos;
    }

    public int getMaxDayByYearMonth(int year, int month) {

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DATE, 1);

        calendar.set(Calendar.YEAR, year);

        calendar.set(Calendar.MONTH, month - 1);

        return calendar.getActualMaximum(Calendar.DATE);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void convertToDraft(Integer financeId) throws SzException {

        DtUsersVo currentUser = DtUsersVo.findCurrentUser();
        String userManageAreaId = currentUser.findUserManageAreaId();
        AxhFinance axhFinance = findFinance(financeId, userManageAreaId, false);

        // 查询状态是否可以转换成草稿
        if (!axhFinance.getCurrentStatus().equals(FinanceStatus.ONE_AUDIT.type) && !axhFinance.getCurrentStatus().equals(FinanceStatus.TURN_ZERO.type)) {
            throw new SzException(SystemCode.QUERY_CHECK_ERROR, "当前状态不能转换成草稿的状态");
        }
        financeMapper.updateFinanceStatus(financeId, userManageAreaId, FinanceStatus.CAO_GAO.type);
        LogUtil.buildFinanceLog(financeId, "【财务报销】用户" + currentUser.getUsername() + "将财务报表转换成草稿状态。", currentUser, axhFinance.getFromToAreaId(), FinanceStatus.CAO_GAO.type);
    }

    @Override
    public List<String> findFinanceAccessory(Integer financeId, Integer lineId) throws SzException {


        DtUsersVo currentUser = DtUsersVo.findCurrentUser();
        AxhFinance finance = findFinance(financeId, currentUser.findUserManageAreaId(), false);
        String tableName = finance.getAreaType() == 1 ? "axh_finance_report_community" : "axh_finance_report_village";
        String images = financeMapper.findFinanceAccessory(lineId, tableName);
        return StringUtils.isEmpty(images) ? null : Arrays.asList(images.split(","));
    }

    @Override
    public AuditTotalVo findAuditTotal(Integer areaType) {

        DtUsersVo currentUser = DtUsersVo.findCurrentUser();
        AuditTotalVo auditTotalVo = new AuditTotalVo();

        FinanceReq financeReq = new FinanceReq();
        financeReq.setAreaType(areaType);
        FinanceAuditSizeVo financeAuditSize = findFinanceAuditSize(financeReq);

        auditTotalVo.setTotalDbSize(financeAuditSize == null ? 0 : (financeAuditSize.getWaitSize() == null ? 0 : financeAuditSize.getWaitSize()) + (financeAuditSize.getTurnDownSize() == null ? 0 : financeAuditSize.getTurnDownSize()));

        // 查询总数
        AuditTotalVo auditTotal = financeMapper.findAuditTotal(financeReq, currentUser.findUserManageAreaId(), currentUser.findUserFinanceLookCurrentStatus(1), currentUser.findUserFinanceLookCurrentStatus(2), currentUser.findUserFinanceLookCurrentStatus(3));
        if (auditTotal == null) {
            auditTotal = new AuditTotalVo();
        }
        auditTotalVo.setLoanTotal(auditTotal.getLoanTotal() == null ? new BigDecimal("0") : auditTotal.getLoanTotal());
        auditTotalVo.setBorrowTotal(auditTotal.getBorrowTotal() == null ? new BigDecimal("0") : auditTotal.getBorrowTotal());
        return auditTotalVo;
    }

    @Override
    public List<FinanceAuditVo> findPublicFinanceList(FinancePublicListReq financePublicListReq) {

        financePublicListReq.format();
        List<FinanceAuditVo> financeAuditVos = financeMapper.findPublicFinanceList(financePublicListReq);
        return financeAuditVos;
    }

    @Override
    public List<AuditLogRecord> findAuditLogRecord(Integer id, Integer type) {

        List<AuditLogRecord> auditLogRecords = financeMapper.findAuditLogRecord(id, type);
        if (StringUtils.isEmpty(auditLogRecords)) {
            for (AuditLogRecord auditLogRecord : auditLogRecords) {
                if (auditLogRecord.getCurrentFinanceStatus() < 0) {
                    auditLogRecord.setIsTurn(1);
                } else {
                    auditLogRecord.setIsTurn(0);
                }
            }
        }
        return auditLogRecords;
    }

    @Override
    public void clearFb(Integer financeId, Integer financeType) throws SzException {
        financeMapper.updateFinanceFb(financeId, 0);
        AxhFinance axhFinance = financeMapper.findFinance(financeId);
        if (axhFinance == null) {
            throw new SzException(SystemCode.QUERY_CHECK_ERROR, "报表不存在");
        }
        // 清空提交的备注信息
        financeMapper.rejectFbFinance(financeId, null, 0);
        if (axhFinance.getAreaType() == 1) { // 等于1 说明是社区的报表
            financeMapper.deleteFinanceFb(financeId, "axh_finance_report_community");
            financeMapper.updateFinanceLineFb(financeId, "axh_finance_report_community");
            financeMapper.updateIsValid2(financeId, "axh_finance_report_community");
        } else if (axhFinance.getAreaType() == 2) { // 等于2 说明是村的报表
            financeMapper.deleteFinanceFb(financeId, "axh_finance_report_village");
            financeMapper.updateFinanceLineFb(financeId, "axh_finance_report_village");
            financeMapper.updateIsValid2(financeId, "axh_finance_report_village");
        }
    }

    @Override
    public void submitFb(Integer financeId) throws SzException {

        AxhFinance axhFinance = financeMapper.findFinance(financeId);
        financeMapper.rejectFbFinance(financeId, null, 1);
        // 发送模板通知的短信
        List<DtUsersVo> dtUserByRoles = financeMapper.findDtUserByRoles(axhFinance.getAreaType().equals(2) ? DtUsersVo.roleIdList.get(4) + "" : DtUsersVo.roleIdList.get(5) + "", axhFinance.getFromToAreaId());
        sendWeChatWarnMsg(axhFinance, null, dtUserByRoles, 1, "您有一条财务审核通知");
    }

    @Override
    public List<NotifyVo> findNotifyList() throws SzException {


        String userManageAreaId = DtUsersVo.findCurrentUser().findUserManageAreaId();
        List<NotifyVo> notifyVos = financeMapper.findNotifyList(StringUtils.hasLength(userManageAreaId) ? userManageAreaId : "-10000000");
        if (!CollectionUtils.isEmpty(notifyVos)) {
            // 发送模板通知
            for (NotifyVo notifyVo : notifyVos) {
                try {
                    WeChatDevUtil.WeChatTemplate.sendFinanceReportAuditWarn(null, notifyVo.getWxOpenId(), new AxhFinance(), notifyVo.getFinanceTitle(), null, "您有一个报表暂未公开【" + notifyVo.getFinanceTitle() + "】", true);
                } catch (SzException e) {
                    e.printStackTrace();
                }
            }
        }
        return notifyVos;
    }

    public static final ThreadPoolExecutor POOL_EXECUTOR = new ThreadPoolExecutor(20, 30, 1, TimeUnit.DAYS, new LinkedBlockingQueue<>());

    @Override
    public FinanceDetailVo financeDetailVo(Integer financeId) throws SzException {


        DtUsersVo currentUser = DtUsersVo.findCurrentUser();
        FinanceDetailVo financeDetailVo = new FinanceDetailVo();

        AxhFinance axhFinance = financeMapper.findFinance(financeId);
        if (axhFinance == null) {
            throw new SzException(SystemCode.QUERY_CHECK_ERROR, "报表不存在");
        }

        // 是否可以查看副本
        String isPublicEntr = request.getParameter("isPublicEntr");
        boolean lookFb = (axhFinance.getCreateUserId().equals(DtUsersVo.findCurrentUser().getId()) || DtUsersVo.findCurrentUser().getUserMaxRole().equals(DtUsersVo.roleIdList.get(4)) || DtUsersVo.findCurrentUser().getUserMaxRole().equals(DtUsersVo.roleIdList.get(5))) && !"1".equals(isPublicEntr);
        axhFinance.setFbStatus(lookFb ? axhFinance.getFbStatus() : null);
        // 判断按钮的状态
        FinanceDetailVo.Btn btn = new FinanceDetailVo.Btn();

        // 判断当前角色与当前进度
        Integer userMaxRole = -1;

        if (currentUser != null) {
            userMaxRole = currentUser.findUserMaxRole();
            btn.setIsSubmit(axhFinance.getCurrentStatus().equals(FinanceStatus.CAO_GAO.type) && axhFinance.getCreateUserId().equals(currentUser.getId()) ? 1 : 0);
            btn.setIsSave(btn.getIsSubmit());
            btn.setIsDel(btn.getIsSubmit());
            btn.setIsCaoGao(axhFinance.getCreateUserId().equals(currentUser.getId()) && (axhFinance.getCurrentStatus().equals(FinanceStatus.ONE_AUDIT.type) || axhFinance.getCurrentStatus().equals(FinanceStatus.TURN_ZERO.type)) ? 1 : 0);
            // btn.setIsSuccess(!axhFinance.getCreateUserId().equals(currentUser.getId()) && !axhFinance.getCurrentStatus().equals(FinanceStatus.CAO_GAO.type) ? 1 : 0);

            if ((axhFinance.getCurrentStatus().equals(FinanceStatus.ONE_AUDIT.type) || axhFinance.getCurrentStatus().equals(FinanceStatus.TURN_ONE.type)) && (userMaxRole == 3 || userMaxRole == 4)) {
                btn.setIsSuccess(1);
            } else if ((userMaxRole == 5 || userMaxRole == 6) && (axhFinance.getCurrentStatus().equals(FinanceStatus.TWO_AUDIT.type) || axhFinance.getCurrentStatus().equals(FinanceStatus.TURN_TWO.type))) {
                btn.setIsSuccess(1);
            } else if (userMaxRole == 7 && axhFinance.getCurrentStatus().equals(FinanceStatus.THREE_AUDIT.type)) {
                btn.setIsSuccess(1);
            }
            btn.setIsTurn(btn.getIsSuccess());

        }
        financeDetailVo.setBtn(btn);
        String isPhone = request.getParameter("isPhone");

        // 查询日志的信息
        List<AxhAuditFinanceLogVo> auditFinanceLogTemp = findAuditFinanceLog(financeId);
        AxhAuditFinanceLogVo financePublicLog = financeMapper.findFinancePublicLog(financeId, FinanceStatus.COMMAND_UPDATE.type);
        List<AxhAuditFinanceLogVo> auditFinanceLog = new ArrayList<>();
        for (int i = auditFinanceLogTemp.size() - 1; i >= 0; i--) {
            auditFinanceLog.add(auditFinanceLogTemp.get(i));
        }
        if (financePublicLog == null || axhFinance.getIsPublic() == 0) {
            financePublicLog = new AxhAuditFinanceLogVo();
            financePublicLog.setWait(1);
            financePublicLog.setTitle("待发布");
        } else {
            financePublicLog.setWait(2);
            financePublicLog.setTitle("已发布");
        }
        auditFinanceLog.add(financePublicLog);

        if (StringUtils.hasLength(isPhone) && "1".equals(isPhone)) {
            auditFinanceLog.remove(0);
            auditFinanceLog.remove(auditFinanceLog.size() - 1);
            auditFinanceLog.get(0).setTitle("财务审批");
            auditFinanceLog.get(1).setTitle("主任审批");
            auditFinanceLog.get(2).setTitle("领导审批");
        }

        POOL_EXECUTOR.execute(() -> {

            financeDetailVo.setAxhFinance(axhFinance);
            financeDetailVo.setFinanceStatus(FinanceAuditVo.getFinalStatus(axhFinance.getCurrentStatus()));
            financeDetailVo.setFinanceStatusStr(FinanceAuditVo.financeStatusStr(financeDetailVo.getFinanceStatus()));
            financeDetailVo.setAxhAuditFinanceLogVos(auditFinanceLog);

            // 判断是否可以转换成草稿的状态
            if (axhFinance.getCurrentStatus() == FinanceStatus.ONE_AUDIT.type) {
                financeDetailVo.setConvertToDraft(IsStatus.YES);
            }

            // 判断是否是驳回
            if (financeDetailVo.getFinanceStatus().equals(3)) {

                if (axhFinance.getCurrentStatus().equals(FinanceStatus.TURN_TWO.type)) {
                    financeDetailVo.setTurnDownMsg(auditFinanceLogTemp.get(0).getRemark());
                } else if (axhFinance.getCurrentStatus().equals(FinanceStatus.TURN_ONE.type)) {
                    financeDetailVo.setTurnDownMsg(auditFinanceLogTemp.get(1).getRemark());
                } else if (axhFinance.getCurrentStatus().equals(FinanceStatus.TURN_ZERO.type)) {
                    financeDetailVo.setTurnDownMsg(auditFinanceLogTemp.get(2).getRemark());
                }
            }
        });
        // 通过类型 查询不同的表信息
        List<FinanceDetailVo.FinanceReport> financeReportBases = new ArrayList<>();

        AtomicInteger totalPzSize = new AtomicInteger(0);
        // 统计进行处理数据
        processFinanceReportDetailFindSonInfo(lookFb, financeReportBases, axhFinance, 0, "", totalPzSize);
        if (axhFinance.getAreaType() == 1) {
            Map<Integer, List<FinanceDetailVo.FinanceReport>> collect = financeReportBases.stream().collect(Collectors.groupingBy(item -> item.getParentBase().getLineType() == null ? 0 : item.getParentBase().getLineType()));
            financeDetailVo.setFinanceReports(collect.get(1));
            financeDetailVo.setFinanceReportsType2(collect.get(2));
        } else {
            financeDetailVo.setFinanceReports(financeReportBases);
        }

        financeDetailVo.setPzSize(totalPzSize.get());
        // 判断是否是副本的状态
        if ("1".equals(axhFinance.getFbStatus() + "") && lookFb) {
            financeDetailVo.setTurnDownMsg(axhFinance.getFbRejectDetail());
            btn.setIsSuccess(userMaxRole == 5 || userMaxRole == 6 ? 1 : 0);
            btn.setIsTurn(userMaxRole == 5 || userMaxRole == 6 ? 1 : 0);
            if (StringUtils.hasLength(financeDetailVo.getTurnDownMsg())) {
                financeDetailVo.setFinanceStatus(3);
                financeDetailVo.setFinanceStatusStr("二次修改被驳回");
            }
        }
        return financeDetailVo;
    }

    private void processFinanceReportDetailFindSonInfo(boolean lookFb, List<FinanceDetailVo.FinanceReport> financeReportBases, AxhFinance finance, Integer pid, String gap, AtomicInteger totalPzSize) {

        List<AxhFinanceReportCommunity> financeReportCommunities = new ArrayList<>();
        List<AxhFinanceReportVillage> financeReportVillages = new ArrayList<>();
        if (finance.getAreaType() == 1) {
            financeReportCommunities = financeMapper.findFinanceDetailCommunities(finance.getId(), pid, lookFb);
        } else {
            financeReportVillages = financeMapper.findFinanceDetailVillage(finance.getId(), pid, lookFb);
        }

        if (!CollectionUtils.isEmpty(financeReportVillages) || !CollectionUtils.isEmpty(financeReportCommunities)) {
            if (!CollectionUtils.isEmpty(financeReportCommunities)) {
                for (AxhFinanceReportCommunity financeReportCommunity : financeReportCommunities) {
                    financeReportCommunity.setLineName(gap + financeReportCommunity.getLineName());
                    if ((financeReportCommunity.getFbStatus() == 2 || (financeReportCommunity.getFbStatus() == 3)) && lookFb) {
                        // 说明有副本的信息
                        AxhFinanceReportCommunity axh_finance_report_community = financeMapper.findFbTemp(financeReportCommunity.getId(), "axh_finance_report_community");
                        financeReportCommunity.setFbTemp(axh_finance_report_community);
                        if (financeReportCommunity.getFbTemp() != null) {
                            financeReportCommunity.setLineName(axh_finance_report_community.getLineName());
                            financeReportCommunity.setLineType(axh_finance_report_community.getLineType());
                            financeReportCommunity.setHeadMoney(axh_finance_report_community.getHeadMoney());
                            financeReportCommunity.setEndMoney(axh_finance_report_community.getEndMoney());
                            financeReportCommunity.setAccessory(axh_finance_report_community.getAccessory());
                        }
                        if (financeReportCommunity.getFbStatus() == 3) {
                            financeReportCommunity.setFbFlag(1);
                        }
                    }
                    financeReportBases.add(new FinanceDetailVo.FinanceReport(financeReportCommunity, new ArrayList<>()));
                    // 判断是否需要处理副本的内容
                    if (StringUtils.hasLength(financeReportCommunity.getAccessory())) {
                        totalPzSize.addAndGet(financeReportCommunity.getAccessory().split(",").length);
                    }
                }
            }
            if (!CollectionUtils.isEmpty(financeReportVillages)) {
                for (AxhFinanceReportVillage financeReportVillage : financeReportVillages) {
                    financeReportVillage.setLineName(gap + financeReportVillage.getLineName());
                    if ((financeReportVillage.getFbStatus() == 2 || (financeReportVillage.getFbStatus() == 3)) && lookFb) {
                        // 说明有副本的信息
                        AxhFinanceReportVillage axh_finance_report_village = financeMapper.findFbTemp2(financeReportVillage.getId(), "axh_finance_report_village");
                        financeReportVillage.setFbTemp(axh_finance_report_village);
                        if (financeReportVillage.getFbTemp() != null) {
                            financeReportVillage.setFinanceNumber(axh_finance_report_village.getFinanceNumber());
                            financeReportVillage.setLineName(axh_finance_report_village.getLineName());
                            financeReportVillage.setHeadMoneyType(axh_finance_report_village.getHeadMoneyType());
                            financeReportVillage.setHeadMoney(axh_finance_report_village.getHeadMoney());
                            financeReportVillage.setCurrentBorrow(axh_finance_report_village.getCurrentBorrow());
                            financeReportVillage.setCurrentLoan(axh_finance_report_village.getCurrentLoan());
                            financeReportVillage.setEndMoneyType(axh_finance_report_village.getEndMoneyType());
                            financeReportVillage.setAccessory(axh_finance_report_village.getAccessory());
                            financeReportVillage.setEndMoney(axh_finance_report_village.getEndMoney());
                        }
                        if (financeReportVillage.getFbStatus() == 3) {
                            financeReportVillage.setFbFlag(1);
                        }
                    }
                    financeReportBases.add(new FinanceDetailVo.FinanceReport(financeReportVillage, new ArrayList<>()));
                    if (StringUtils.hasLength(financeReportVillage.getAccessory())) {
                        totalPzSize.addAndGet(financeReportVillage.getAccessory().split(",").length);
                    }
                }
            }
            if (!CollectionUtils.isEmpty(financeReportBases)) {
                for (FinanceDetailVo.FinanceReport financeReportBase : financeReportBases) {
                    processFinanceReportDetailFindSonInfo(lookFb, financeReportBase.getChildren(), finance, financeReportBase.getParentBase().getId(), gap + "  ", totalPzSize);
                }
            }
        }
    }

    public AxhFinance findFinance(Integer id, String userManageAreaId, Boolean caoGao) throws SzException {
        // 查询报表的信息
        AxhFinance finance = financeMapper.findFinanceAndManageAreaId(id, userManageAreaId);
        if (finance == null) {
            throw new SzException(SystemCode.QUERY_CHECK_ERROR, "报表查询为空");
        } else if (!finance.getCurrentStatus().equals(FinanceStatus.CAO_GAO.type) && caoGao) {
            throw new SzException(SystemCode.QUERY_CHECK_ERROR, "该报表已提交审核，请勿重复提交。");
        }

        return finance;
    }

    /**
     * 发送微信提醒模版
     *
     * @param finance
     * @throws SzException
     */
    public void sendWeChatWarnMsg(AxhFinance finance, FinanceStatus financeStatus, List<DtUsersVo> currentAuditDtUsers, Integer submitFb, String title) throws SzException {
        try {
            currentAuditDtUsers = !CollectionUtils.isEmpty(currentAuditDtUsers) ? currentAuditDtUsers : findCurrentAuditDtUsers(financeStatus, finance);

            log.info("currentAuditDtUsers: {}", JSON.toJSONString(currentAuditDtUsers));
            if (!CollectionUtils.isEmpty(currentAuditDtUsers)) {

                for (DtUsersVo currentAuditDtUser : currentAuditDtUsers) {
                    if (StringUtils.isEmpty(currentAuditDtUser.getWxOpenId())) {
                        log.info("用户： {} 没有绑定微信", currentAuditDtUser.getId());
                        continue;
                    }
                    WeChatDevUtil.WeChatTemplate.sendFinanceReportAuditWarn(currentAuditDtUser.getId(), currentAuditDtUser.getWxOpenId(), finance, finance.getFinanceTitle(), submitFb, title, false);
                }
            }
        } catch (SzException e) {
            e.printStackTrace();
            log.info("发送微信失败: {}", e.getMessage());
        }
    }

    /**
     * 查询当前报表状态下，提交审核后应该给谁发通知
     *
     * @param financeStatus
     * @return
     */
    public List<DtUsersVo> findCurrentAuditDtUsers(FinanceStatus financeStatus, AxhFinance axhFinance) throws SzException {

        if (financeStatus == FinanceStatus.CAO_GAO) {
            return null;
        } else if (financeStatus == FinanceStatus.ONE_AUDIT || financeStatus == FinanceStatus.TURN_ONE) {

            // 说明找对应小区的代理会计
            return financeMapper.findDtUserByRoles(axhFinance.getAreaType().equals(2) ? DtUsersVo.roleIdList.get(2) + "" : DtUsersVo.roleIdList.get(3) + "", axhFinance.getFromToAreaId());
        } else if (financeStatus == FinanceStatus.TWO_AUDIT || financeStatus == FinanceStatus.TURN_TWO) {

            // 说明找对应小区的主任信息
            return financeMapper.findDtUserByRoles(axhFinance.getAreaType().equals(2) ? DtUsersVo.roleIdList.get(4) + "" : DtUsersVo.roleIdList.get(5) + "", axhFinance.getFromToAreaId());
        } else if (financeStatus == FinanceStatus.THREE_AUDIT) {

            // 找到分管领导
            return financeMapper.findDtUserByRoles(DtUsersVo.roleIdList.get(6) + "", axhFinance.getFromToAreaId());
        } else if (financeStatus == FinanceStatus.TURN_ZERO || financeStatus == FinanceStatus.PASS_AUDIT) {
            return financeMapper.findDtUserByRoles(axhFinance.getAreaType().equals(2) ? DtUsersVo.roleIdList.get(0) + "" : DtUsersVo.roleIdList.get(1) + "", axhFinance.getFromToAreaId());
        }

        return null;
    }

    @Override
    public List<AxhAuditFinanceLogVo> findAuditFinanceLog(Integer id) {


        AxhFinance axhFinance = financeMapper.findFinance(id);
        if (axhFinance == null) {
            return new ArrayList<>();
        }

        // 根据当前报表的状态组成报表
        Integer currentStatus = axhFinance.getCurrentStatus();

        AxhAuditFinanceLogVo submitExcelVo = null;
        AxhAuditFinanceLogVo oneAuditExcelVo = null;
        // 查询二级的审核信息
        AxhAuditFinanceLogVo twoAuditExcelVo = null;
        AxhAuditFinanceLogVo threeAuditExcelVo = null;

        if (currentStatus.equals(FinanceStatus.CAO_GAO.type)) {
            // 说明村社区提交了报表审核
            submitExcelVo = new AxhAuditFinanceLogVo();
            submitExcelVo.setTitle("待提交");
            submitExcelVo.setWait(0);

            oneAuditExcelVo = new AxhAuditFinanceLogVo();
            oneAuditExcelVo.setWait(1);
            oneAuditExcelVo.setTitle(axhFinance.getAreaType().equals(2) ? "代理会计" : "会计");

            twoAuditExcelVo = new AxhAuditFinanceLogVo();
            twoAuditExcelVo.setWait(1);
            twoAuditExcelVo.setTitle(axhFinance.getAreaType().equals(2) ? "经发办主任" : "财经办主任");

            threeAuditExcelVo = new AxhAuditFinanceLogVo();
            threeAuditExcelVo.setWait(1);
            threeAuditExcelVo.setTitle("分管领导");

        } else if (currentStatus.equals(FinanceStatus.ONE_AUDIT.type)) {
            // 说明村社区提交了报表审核
            submitExcelVo = financeMapper.findFinanceLog(id, FinanceStatus.ONE_AUDIT.type);
            submitExcelVo.setTitle("提交报表");
            submitExcelVo.setWait(2);

            oneAuditExcelVo = new AxhAuditFinanceLogVo();
            oneAuditExcelVo.setWait(0);
            oneAuditExcelVo.setTitle(axhFinance.getAreaType().equals(2) ? "代理会计审核" : "会计审核");

            twoAuditExcelVo = new AxhAuditFinanceLogVo();
            twoAuditExcelVo.setWait(1);
            twoAuditExcelVo.setTitle(axhFinance.getAreaType().equals(2) ? "经发办主任审核" : "财经办主任审核");

            threeAuditExcelVo = new AxhAuditFinanceLogVo();
            threeAuditExcelVo.setWait(1);
            threeAuditExcelVo.setTitle("分管领导审核");

        } else if (currentStatus.equals(FinanceStatus.TWO_AUDIT.type)) {
            // 说明代理会计通过审核了
            submitExcelVo = financeMapper.findFinanceLog(id, FinanceStatus.ONE_AUDIT.type);
            submitExcelVo.setTitle("提交报表");
            submitExcelVo.setWait(2);

            oneAuditExcelVo = financeMapper.findFinanceLog(id, FinanceStatus.TWO_AUDIT.type);
            oneAuditExcelVo.setWait(2);
            oneAuditExcelVo.setTitle(axhFinance.getAreaType().equals(2) ? "代理会计审核" : "会计审核");

            twoAuditExcelVo = new AxhAuditFinanceLogVo();
            twoAuditExcelVo.setWait(0);
            twoAuditExcelVo.setTitle(axhFinance.getAreaType().equals(2) ? "经发办主任审核" : "财经办主任审核");

            threeAuditExcelVo = new AxhAuditFinanceLogVo();
            threeAuditExcelVo.setWait(1);
            threeAuditExcelVo.setTitle("分管领导审核");

        } else if (currentStatus.equals(FinanceStatus.THREE_AUDIT.type)) {
            // 说明经发办主任通过审核了
            submitExcelVo = financeMapper.findFinanceLog(id, FinanceStatus.ONE_AUDIT.type);
            submitExcelVo.setTitle("提交报表");
            submitExcelVo.setWait(2);

            oneAuditExcelVo = financeMapper.findFinanceLog(id, FinanceStatus.TWO_AUDIT.type);
            oneAuditExcelVo.setWait(2);
            oneAuditExcelVo.setTitle(axhFinance.getAreaType().equals(2) ? "代理会计审核" : "会计审核");

            twoAuditExcelVo = financeMapper.findFinanceLog(id, FinanceStatus.THREE_AUDIT.type);
            twoAuditExcelVo.setWait(2);
            twoAuditExcelVo.setTitle(axhFinance.getAreaType().equals(2) ? "经发办主任审核" : "财经办主任审核");

            threeAuditExcelVo = new AxhAuditFinanceLogVo();
            threeAuditExcelVo.setWait(0);
            threeAuditExcelVo.setTitle("分管领导审核");

        } else if (currentStatus.equals(FinanceStatus.PASS_AUDIT.type)) {
            // 说明分管领导审核通过审核了
            // 说明代理会计通过审核了
            submitExcelVo = financeMapper.findFinanceLog(id, FinanceStatus.ONE_AUDIT.type);
            submitExcelVo.setTitle("提交报表");
            submitExcelVo.setWait(2);

            oneAuditExcelVo = financeMapper.findFinanceLog(id, FinanceStatus.TWO_AUDIT.type);
            oneAuditExcelVo.setWait(2);
            oneAuditExcelVo.setTitle(axhFinance.getAreaType().equals(2) ? "代理会计审核" : "会计审核");

            twoAuditExcelVo = financeMapper.findFinanceLog(id, FinanceStatus.THREE_AUDIT.type);
            twoAuditExcelVo.setWait(2);
            twoAuditExcelVo.setTitle(axhFinance.getAreaType().equals(2) ? "经发办主任审核" : "财经办主任审核");

            threeAuditExcelVo = financeMapper.findFinanceLog(id, FinanceStatus.PASS_AUDIT.type);
            threeAuditExcelVo.setTitle("分管领导审核");
            threeAuditExcelVo.setWait(2);
        } else if (currentStatus.equals(FinanceStatus.TURN_TWO.type)) {
            // 驳回到了经发办主任，分管领导拒绝通过
            submitExcelVo = financeMapper.findFinanceLog(id, FinanceStatus.ONE_AUDIT.type);
            submitExcelVo.setTitle("提交报表");
            submitExcelVo.setWait(2);

            oneAuditExcelVo = financeMapper.findFinanceLog(id, FinanceStatus.TWO_AUDIT.type);
            oneAuditExcelVo.setWait(2);
            oneAuditExcelVo.setTitle(axhFinance.getAreaType().equals(2) ? "代理会计审核" : "会计审核");

            twoAuditExcelVo = new AxhAuditFinanceLogVo();
            twoAuditExcelVo.setWait(0);
            twoAuditExcelVo.setTitle(axhFinance.getAreaType().equals(2) ? "经发办主任审核" : "财经办主任审核");

            threeAuditExcelVo = financeMapper.findFinanceLog(id, FinanceStatus.TURN_TWO.type);
            threeAuditExcelVo.setWait(3);
            threeAuditExcelVo.setTitle("分管领导审核");

        } else if (currentStatus.equals(FinanceStatus.TURN_ONE.type)) {
            // 驳回到了代理会计，经发办主任拒绝通过
            submitExcelVo = financeMapper.findFinanceLog(id, FinanceStatus.ONE_AUDIT.type);
            submitExcelVo.setTitle("提交报表");
            submitExcelVo.setWait(2);

            oneAuditExcelVo = new AxhAuditFinanceLogVo();
            oneAuditExcelVo.setWait(0);
            oneAuditExcelVo.setTitle(axhFinance.getAreaType().equals(2) ? "代理会计审核" : "会计审核");

            twoAuditExcelVo = financeMapper.findFinanceLog(id, FinanceStatus.TURN_ONE.type);
            twoAuditExcelVo.setWait(3);
            twoAuditExcelVo.setTitle(axhFinance.getAreaType().equals(2) ? "经发办主任审核" : "财经办主任审核");

            threeAuditExcelVo = new AxhAuditFinanceLogVo();
            threeAuditExcelVo.setWait(1);
            threeAuditExcelVo.setTitle("分管领导审核");
        } else if (currentStatus.equals(FinanceStatus.TURN_ZERO.type)) {
            // 驳回到了驳回到村、社区 , 代理会计拒绝通过
            submitExcelVo = financeMapper.findFinanceLog(id, FinanceStatus.ONE_AUDIT.type);
            submitExcelVo.setTitle("等待重新提交");
            submitExcelVo.setWait(0);

            oneAuditExcelVo = financeMapper.findFinanceLog(id, FinanceStatus.TURN_ZERO.type);
            oneAuditExcelVo.setWait(3);
            oneAuditExcelVo.setTitle(axhFinance.getAreaType().equals(2) ? "代理会计审核" : "会计审核");

            twoAuditExcelVo = new AxhAuditFinanceLogVo();
            twoAuditExcelVo.setWait(1);
            twoAuditExcelVo.setTitle(axhFinance.getAreaType().equals(2) ? "经发办主任审核" : "财经办主任审核");

            threeAuditExcelVo = new AxhAuditFinanceLogVo();
            threeAuditExcelVo.setWait(1);
            threeAuditExcelVo.setTitle("分管领导审核");
        }

        List<AxhAuditFinanceLogVo> axhAuditFinanceLogVos = new ArrayList<>();
        axhAuditFinanceLogVos.add(threeAuditExcelVo);
        axhAuditFinanceLogVos.add(twoAuditExcelVo);
        axhAuditFinanceLogVos.add(oneAuditExcelVo);
        axhAuditFinanceLogVos.add(submitExcelVo);

        return axhAuditFinanceLogVos;
    }

    /**
     * 解析社区的Excel表数据
     *
     * @param file
     */
    public void parseCommunityExcel(MultipartFile file, Integer financeType) throws IOException {

        // 读取Excel
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        List<List<Object>> readList = reader.read();
        List<FinanceReportBase> communitiesLine1 = new ArrayList<>(), communitiesLine2 = new ArrayList<>();

        // 处理Excel的数据 ，转换成两个资产和负债和净资产两个集合的数据
        if (financeType == 1) { // 等于1 说明是社区的报表
            processReadListToHeadAndEndReportList(readList, communitiesLine1, communitiesLine2);
        } else if (financeType == 2) { // 等于2 说明是村的报表
            processReadListToHeadAndEndReportVillageList(readList, communitiesLine1, communitiesLine2);
        }
        List<ExportCommunityVo> exportCommunityVos = new ArrayList<>();

        processHeadAndEndReportListToCommunityList(communitiesLine1, exportCommunityVos);
        processHeadAndEndReportListToCommunityList(communitiesLine2, exportCommunityVos);


        // 新建报表的信息
        AxhFinance axhFinance = buildFinance(financeType);


        // 遍历树节点的信息，存入数据库中
        for (ExportCommunityVo exportCommunityVo : exportCommunityVos) {

            FinanceReportBase item = exportCommunityVo.getItem();
            item.setFinanceId(axhFinance.getId());

            item.setLineName(item.getLineName().trim());
            // 判断是什么类型的
            if (financeType == 1) {
                AxhFinanceReportCommunity item1 = (AxhFinanceReportCommunity) item;
                if ("资产总计".equals(item1.getLineName())) {
                    axhFinance.setBorrowTotalMoney(item1.getEndMoney());
                } else if ("负债和净资产总计".equals(item1.getLineName())) {
                    axhFinance.setLoanTotalMoney(item1.getEndMoney());
                }

                axhFinanceReportCommunityMapper.insertSelective(item1);

            } else {
                AxhFinanceReportVillage item1 = (AxhFinanceReportVillage) item;
                if ("合计".equals(item1.getLineName())) {
                    axhFinance.setBorrowTotalMoney(item1.getCurrentBorrow());
                    axhFinance.setLoanTotalMoney(item1.getCurrentLoan());
                }
                axhFinanceReportVillageMapper.insertSelective(item1);
            }

            parseTree(exportCommunityVo, axhFinance.getId(), financeType);
        }

        axhFinanceMapper.updateByPrimaryKeySelective(axhFinance);
    }

    private AxhFinance buildFinance(Integer type) {
        // 创建报表的数据信息
        AxhFinance axhFinance = new AxhFinance();
        DtUsersVo currentUser = DtUsersVo.findCurrentUser();
        // 获取该用户的管辖村的信息数据
        DtNewsSort dtNewsSort = financeMapper.findUserManageAreaLimit1(currentUser.getId());
        axhFinance.setCreateTime(getLastMonth());
        axhFinance.setFinanceTitle(dtNewsSort.getName() + "-" + DateUtil.format(getLastMonth(), "yyyy年MM月") + (type == 1 ? "资产负债表" : "科目余额表"));
        axhFinance.setFromToAreaId(dtNewsSort.getId());
        axhFinance.setCreateUserId(currentUser.getId());
        axhFinance.setAreaType(type);
        axhFinance.setCurrentStatus(FinanceStatus.CAO_GAO.type);
        axhFinanceMapper.insertSelective(axhFinance);

        // 构建财务日志的信息
        LogUtil.buildFinanceLog(axhFinance.getId(), "【财务报销】用户" + currentUser.getUsername() + "创建了财务报表，并导入了Excel。", currentUser, dtNewsSort.getId(), FinanceStatus.COMMAND_UPDATE.type);
        return axhFinance;
    }

    /**
     * 获取上个月月份
     *
     * @return
     */
    public static Date getLastMonth() {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        // 设置为当前时间
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, -1);
        // 设置为上一个月
        //calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
        date = calendar.getTime();
        return date;
    }

    public void parseTree(ExportCommunityVo exportCommunityVo, Integer id, Integer financeType) {


        // 遍历当层的所有子类信息
        List<ExportCommunityVo> exportCommunityVos = new ArrayList<>();
        if (exportCommunityVo.getSonCom() != null) {
            exportCommunityVo.getSonCom().getItem().setFinanceId(id); //    报表id
            exportCommunityVo.getSonCom().getItem().setPid(exportCommunityVo.getItem().getId());    // 所属父类
            exportCommunityVo.getSonCom().getItem().setLineName(exportCommunityVo.getSonCom().getItem().getLineName().trim());
            exportCommunityVos.add(exportCommunityVo.getSonCom());
            // 定义当前父亲的所有儿子的数据信息
            ExportCommunityVo nextVo = exportCommunityVo.getSonCom();
            while (nextVo.getNextVo() != null) {
                nextVo = nextVo.getNextVo();
                nextVo.getItem().setFinanceId(id); //    报表id
                nextVo.getItem().setPid(exportCommunityVo.getItem().getId());    // 所属父类
                nextVo.getItem().setLineName(nextVo.getItem().getLineName().trim());
                exportCommunityVos.add(nextVo);
            }
        }

        // 存入到MySQL
        if (!CollectionUtils.isEmpty(exportCommunityVos)) {

            if (financeType == 1) {
                financeMapper.batchSaveFinance(exportCommunityVos);
            } else {
                financeMapper.batchSaveFinanceVillage(exportCommunityVos);
            }


            for (ExportCommunityVo communityVo : exportCommunityVos) {
                parseTree(communityVo, id, financeType);
            }
        }


    }

    public void processHeadAndEndReportListToCommunityList(List<FinanceReportBase> communitiesLine1, List<ExportCommunityVo> exportCommunityVos) {

        if (!CollectionUtils.isEmpty(communitiesLine1)) {
            ExportCommunityVo currentVo = null;
            ExportCommunityVo currentAppendParentVo = null;

            for (int i = 0; i < communitiesLine1.size(); i++) {
                FinanceReportBase reportCommunity = communitiesLine1.get(i);

                if (subStringIndexIsGap(reportCommunity, 0, 2)) {

                    ExportCommunityVo appendVo = new ExportCommunityVo(reportCommunity);
                    if (!subStringIndexIsGap(reportCommunity, 2, 4)) {
                        // 说明就是第二层的数据
                        currentAppendParentVo = appendVo;
                        appendVo.setParentVo(currentVo);
                        if (currentVo.getSonCom() == null) {
                            currentVo.setSonCom(appendVo);
                        } else {
                            ExportCommunityVo sonNextVo = currentVo.getSonCom();
                            while (sonNextVo.getNextVo() != null) {
                                sonNextVo = sonNextVo.getNextVo();
                            }
                            sonNextVo.setNextVo(appendVo);
                        }

                    } else {
                        appendVo.setParentVo(currentAppendParentVo);
                        // 说明涉及到了多层的一个报表信息
                        int index = 2;
                        if (currentAppendParentVo.getSonCom() == null) {
                            currentAppendParentVo.setSonCom(appendVo);
                        } else {
                            ExportCommunityVo sonNextVo = currentAppendParentVo.getSonCom();
                            while (sonNextVo.getNextVo() != null) {
                                sonNextVo = sonNextVo.getNextVo();
                            }
                            sonNextVo.setNextVo(appendVo);
                        }

                        // 判断下一个列与当前这个列相差多少级 需要回溯到什么之前
                        if (i + 1 < communitiesLine1.size()) {
                            // 获取开头包含多少个空格的信息

                            int gapSize = includeGap(communitiesLine1.get(i + 1).getLineName()) / 2;
                            int currentGapSize = includeGap(communitiesLine1.get(i).getLineName()) / 2;

                            ExportCommunityVo exportCommunityVo = null;
                            for (int gapSizeI = 0; gapSizeI <= (currentGapSize - gapSize); gapSizeI++) {
                                exportCommunityVo = exportCommunityVo == null ? appendVo.getParentVo() : exportCommunityVo.getParentVo();
                                currentAppendParentVo = exportCommunityVo;
                            }
                        }
                        while (index * 2 < reportCommunity.getLineName().length() && StringUtils.isEmpty(reportCommunity.getLineName().substring(0, index * 2).trim())) {
                            index++;
                        }
                        // 判断是否需要将当前这个VO变成 currentAppendParentVo ，如果下一个出现了他的子，那么则需要
                        if (i + 1 < communitiesLine1.size() && index * 2 < communitiesLine1.get(i + 1).getLineName().length() && StringUtils.isEmpty(communitiesLine1.get(i + 1).getLineName().substring(0, index * 2).trim())) {
                            currentAppendParentVo = appendVo;
                        }

                    }

                } else {
                    // 封装parent的信息
                    // 顶级的父亲只有下一级
                    ExportCommunityVo currentVoTemp = new ExportCommunityVo(reportCommunity);
                    if (currentVo != null) {
                        currentVo.setNextVo(currentVoTemp);
                        // 设置新的父层的上一个父信息
                        currentVoTemp.setLastVo(currentVo);
                    }
                    currentVo = currentVoTemp;
                    exportCommunityVos.add(currentVoTemp);
                }
            }
        }
    }

    private boolean subStringIndexIsGap(FinanceReportBase reportCommunity, int beginIndex, int endIndex) {
        return reportCommunity.getLineName().length() > endIndex && reportCommunity.getLineName().substring(beginIndex, endIndex).equals("  ");
    }

    public int includeGap(String text) {
        int gapSize = 0;
        if (!StringUtils.isEmpty(text)) {
            while (text.charAt(gapSize) == ' ') {
                gapSize++;
            }
        }

        return gapSize;
    }

    private void processReadListToHeadAndEndReportVillageList(List<List<Object>> readList, List<FinanceReportBase> communitiesLine1, List<FinanceReportBase> communitiesLine2) {

        if (!CollectionUtils.isEmpty(readList)) {
            for (int i = 0; i < readList.size(); i++) {
                if (i < 5 || i >= readList.size() - 2) continue;
                List<Object> objects = readList.get(i);
                AxhFinanceReportVillage axhFinanceReportVillage = new AxhFinanceReportVillage();
                axhFinanceReportVillage.setFinanceNumber(StringUtils.isEmpty(objects.get(0)) ? "" : objects.get(0).toString());
                axhFinanceReportVillage.setLineName(StringUtils.isEmpty(objects.get(1)) ? "" : objects.get(1).toString());
                axhFinanceReportVillage.setLineName(axhFinanceReportVillage.getLineName().replaceAll(" ", ""));
                axhFinanceReportVillage.setHeadMoneyType(StringUtils.isEmpty(objects.get(2)) ? "" : objects.get(2).toString());
                axhFinanceReportVillage.setHeadMoney(StringUtils.isEmpty(objects.get(3)) ? null : new BigDecimal(objects.get(3).toString().replaceAll(",", "")));
                axhFinanceReportVillage.setCurrentBorrow(StringUtils.isEmpty(objects.get(4)) ? null : new BigDecimal(objects.get(4).toString().replaceAll(",", "")));
                axhFinanceReportVillage.setCurrentLoan(StringUtils.isEmpty(objects.get(5)) ? null : new BigDecimal(objects.get(5).toString().replaceAll(",", "")));
                axhFinanceReportVillage.setEndMoneyType(StringUtils.isEmpty(objects.get(6)) ? "" : objects.get(6).toString());
                axhFinanceReportVillage.setEndMoney(StringUtils.isEmpty(objects.get(7)) ? null : new BigDecimal(objects.get(7).toString().replaceAll(",", "")));
                communitiesLine1.add(axhFinanceReportVillage);
            }
        }
    }

    /**
     * 处理Excel的数据 ，转换成两个资产和负债和净资产两个集合的数据
     *
     * @param readList
     */
    private void processReadListToHeadAndEndReportList(List<List<Object>> readList, List<FinanceReportBase> communitiesLine1, List<FinanceReportBase> communitiesLine2) {
        if (!CollectionUtils.isEmpty(readList)) {
            // 控制左右
            for (int control = 0; control < 2; control++) {
                System.out.println();
                for (int i = 0; i < readList.size(); i++) {
                    int lineIndex = control * 3;
                    List<Object> oneLine = readList.get(i);
                    if (i < 2) {
                        continue;
                    }

                    AxhFinanceReportCommunity reportCommunityLine1 = new AxhFinanceReportCommunity();
                    reportCommunityLine1.setLineType(control + 1);

                    reportCommunityLine1.setLineName(lineIndex < oneLine.size() ? oneLine.get(lineIndex) == null ? "" : oneLine.get(lineIndex).toString() : "");
                    reportCommunityLine1.setLineName(reportCommunityLine1.getLineName().replaceAll(" ", ""));
                    reportCommunityLine1.setHeadMoney(lineIndex + 2 < oneLine.size() ? oneLine.get(lineIndex + 2) == null || StringUtils.isEmpty(oneLine.get(lineIndex + 2).toString()) ? null : new BigDecimal(oneLine.get(lineIndex + 2).toString().replaceAll(",", "")) : null);
                    reportCommunityLine1.setEndMoney(lineIndex + 1 < oneLine.size() ? oneLine.get(lineIndex + 1) == null || StringUtils.isEmpty(oneLine.get(lineIndex + 1).toString()) ? null : new BigDecimal(oneLine.get(lineIndex + 1).toString().replaceAll(",", "")) : null);

                    if (control == 0) {
                        communitiesLine1.add(reportCommunityLine1);
                    } else {
                        communitiesLine2.add(reportCommunityLine1);
                    }

                }
            }
        }
    }

}
